package campshop.daos;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import campshop.models.AddressInfo;
public class AddressInfoDao extends JdbcDaoSupport{
	public long addAddressInfo(AddressInfo ai)
	{
		String sql = "insert into " +
				"tbl_address_info (cs_uId, ai_sAddress, ai_sReceiver, ai_sPhoneNumber)" +
				" values (?, ?, ?, ?)";
		if(super.getJdbcTemplate().update(sql, ai.getuUserId(), ai.getsAddress(), ai.getsReceiver(), ai.getsPhoneNumber())>0){
			return super.getJdbcTemplate().queryForInt("select max(ai_uId) from tbl_address_info");
		}else return 0L;
	}
	
	public boolean delAddressInfo(long uAddressId)
	{
		String sql = "delete from tbl_address_info where ai_uId = ?";
		if(super.getJdbcTemplate().update(sql, uAddressId)>0) return true;
		return false;
	}
	
	public boolean updateAddressInfo(AddressInfo ai) {
		String sql="update tbl_address_info " +
				"set ai_sAddress= ?, ai_sReceiver= ?, ai_sPhoneNumber= ?" +
				"where ai_uId = ?";
		if(super.getJdbcTemplate().update(sql, ai.getsAddress(), ai.getsReceiver(), ai.getsPhoneNumber(), ai.getuAddressId())>0){
			return true;
		}else return false;
	}
	
	public AddressInfo getAddressInfo(long uAddressId)
	{
		String sql = "select * from tbl_address_info where ai_uId=" + uAddressId;
		return (AddressInfo)super.getJdbcTemplate().queryForObject(sql, new AddressInfoRowMapper());
	}
	
	//每个用户可以拥有多个地址
	public List<AddressInfo> getAddressInfoListByUerId(long uId)
	{
		String sql = "select * from tbl_address_info where cs_uId=" + uId;
		return super.getJdbcTemplate().query(sql, new AddressInfoRowMapper());
	}
	class AddressInfoRowMapper implements RowMapper<AddressInfo>{
		@Override
		public AddressInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
			AddressInfo ai = new AddressInfo();
			ai.setuAddressId(rs.getLong("ai_uId"));
			ai.setuUserId(rs.getLong("cs_uId"));
			ai.setsAddress(rs.getString("ai_sAddress"));
			ai.setsReceiver(rs.getString("ai_sReceiver"));
			ai.setsPhoneNumber(rs.getString("ai_sPhoneNumber"));
			return ai;
		}	
	}
}